﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Scaredfinger.JSShell;
using System.IO;
using System.ComponentModel;
using System.Reflection;
using System.Threading;

namespace SampleShell
{  
  public class SampleShell : Shell
  {
    public TextWriter Output
    {
      get;
      set;
    }

    public SampleShell()
      : this(Console.Out)
    {
    }

    public SampleShell(TextWriter output)
    {
      Output = output;
    }

    [ShellOperation]
    [Description("Shows this help screen")]
    public void Help()
    {
      foreach (var method in GetType().GetMethods().Where(x => x.GetCustomAttributes(typeof(ShellOperationAttribute), false).Any()))
      {
        var attr = method.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute;
        
        var parameters = string.Join(",", 
          (
            from p in method.GetParameters()
            select string.Format("{0} {1}", p.ParameterType.Name, p.Name)
          ).ToArray()
        ) ;

        var text = string.Format("\t{0} {1}({2}):\t{3}", method.ReturnType.Name, method.Name, parameters,
          attr == null? "" : attr.Description);

        Print(text);
      }
    }

    [ShellOperation]
    [Description("Prints a text")]
    public void Print(string text)
    {
        Output.WriteLine(text);
    }

    [ShellOperation]
    [Description("Loads a JS file from CWD")]
    public void load(string file)
    {
        try
        {
            string filePath = Directory.GetCurrentDirectory();
            //Console.WriteLine("The current directory is {0}", filePath);

            StreamReader streamReader = new StreamReader(filePath + "/" + file);
            string text = streamReader.ReadToEnd();
            streamReader.Close();

            var result = this.Eval(text);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }

    [ShellOperation]
    [Description("Closes this shell")]
    public void delay(int timeX)
    {
        Thread.Sleep(timeX); 
    }

    [ShellOperation]
    [Description("Closes this shell")]
    public void Exit()
    {
      CloseShell();
    }

  }
}
